
// <copyright file="AbstractMetricsEnabledComponent.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   The abstract metrics enabled component.
// </summary>

namespace SubhadraSolutions.Sharp.Utils.Diagnostics.Performance
{
    /// <summary>
    /// The abstract metrics enabled component.
    /// </summary>
    /// <typeparam name="T">
    /// </typeparam>
    public abstract class AbstractMetricsEnabledComponent<T> : AbstractInitializableAndDisposable
        where T : class
    {
        #region Fields

        /// <summary>
        /// The is added to perf manager
        /// </summary>
        private bool isAddedToPerfManager;

        #endregion Fields

        #region Constructors and Finalizers

        /// <summary>
        /// Initializes a new instance of the <see cref="AbstractMetricsEnabledComponent{T}"/> class.
        /// </summary>
        protected AbstractMetricsEnabledComponent()
        {
            this.CounterStorageType = CounterStorageType.None;
        }

        #endregion Constructors and Finalizers

        #region Public Properties

        /// <summary>
        /// Gets or sets the counter storage type.
        /// </summary>
        public CounterStorageType CounterStorageType { get; set; }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name { get; set; }

        #endregion Public Properties

        #region Methods

        /// <summary>
        /// The dispose.
        /// </summary>
        /// <param name="disposing">
        /// The disposing.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (this.isAddedToPerfManager)
            {
                PerfCounterManager.Instance.RemoveInstance(this as T);
                this.isAddedToPerfManager = false;
            }
        }

        /// <summary>
        /// The initialize protected.
        /// </summary>
        protected override void InitializeProtected()
        {
            if (this.CounterStorageType != CounterStorageType.None)
            {
                this.registerToPerfManager();
                this.isAddedToPerfManager = true;
            }
        }

        /// <summary>
        /// The register to perf manager.
        /// </summary>
        protected virtual void registerToPerfManager()
        {
            PerfCounterManager.Instance.AddInstance(this as T, this.Name, this.CounterStorageType);
        }

        #endregion Methods
    }
}